#ifndef ADAPTIVEFILELAYOUT_H
#define ADAPTIVEFILELAYOUT_H

#include <QLayout>
#include <QLayoutItem>
#include <QRect>
#include <QSize>
#include <QList>
#include <QWidget>
#include <QPropertyAnimation>
#include <QParallelAnimationGroup>
#include <QTimer>
#include "responsivefilelistengine.h"

/**
 * 🎨 AdaptiveFileLayout - 自适应文件布局管理器
 *
 * 核心特性：
 * 1. 动态列数计算：根据容器宽度和DisplayMode智能调整列数
 * 2. 智能间距调整：保持视觉平衡的间距策略
 * 3. 流畅动画过渡：布局变化时的优雅动画效果
 * 4. 性能优化：惰性计算和缓存机制
 * 5. Sony设计风格：符合设计语言的间距和排列
 *
 * 布局策略：
 * - Micro模式：紧密排列，最大化空间利用
 * - Compact模式：平衡间距和密度
 * - Standard模式：舒适的视觉间距
 * - Expanded模式：宽松布局，强调内容
 * - Full模式：豪华间距，完整信息展示
 */

class AdaptiveFileLayout : public QLayout
{
    Q_OBJECT

public:
    explicit AdaptiveFileLayout(QWidget* parent = nullptr);
    ~AdaptiveFileLayout() override;

    // === QLayout接口实现 ===
    void addItem(QLayoutItem* item) override;
    QLayoutItem* itemAt(int index) const override;
    QLayoutItem* takeAt(int index) override;
    int count() const override;

    QSize sizeHint() const override;
    QSize minimumSize() const override;
    void setGeometry(const QRect& rect) override;
    bool hasHeightForWidth() const override { return true; }
    int heightForWidth(int width) const override;

    // === 响应式布局特性 ===
    void setResponsiveEngine(ResponsiveFileListEngine* engine);
    ResponsiveFileListEngine* getResponsiveEngine() const { return m_engine; }

    // === 布局控制 ===
    void setColumns(int columns);
    int getColumns() const { return m_columns; }

    void setSpacing(int spacing);
    int getSpacing() const { return m_spacing; }

    void setMargins(int left, int top, int right, int bottom);
    void setMargins(int margin) { setMargins(margin, margin, margin, margin); }

    // === 动画控制 ===
    void setAnimationEnabled(bool enabled);
    bool isAnimationEnabled() const { return m_animationEnabled; }

    void setAnimationDuration(int duration);
    int getAnimationDuration() const { return m_animationDuration; }

    // === 性能优化 ===
    void enablePerformanceMode(bool enabled);
    void setUpdateThrottleInterval(int msec);

    // === 布局信息查询 ===
    int calculateOptimalColumns(int containerWidth) const;
    QSize calculateItemSize(SonyIveDesign::DisplayMode mode) const;
    int calculateRowCount() const;
    QRect getItemGeometry(int index) const;

    // === 调试和诊断 ===
    QString getLayoutDebugInfo() const;
    void dumpLayoutStructure() const;

    // === 便利方法（兼容现有代码） ===
    void addWidget(QWidget* widget);
    int getCurrentColumns() const { return m_columns; }
    int getRowsCount() const { return calculateRowCount(); }

public slots:
    void onDisplayModeChanged(SonyIveDesign::DisplayMode newMode, SonyIveDesign::DisplayMode oldMode);
    void onContainerResized();
    void updateLayout();
    void invalidateLayout();

signals:
    void layoutUpdateStarted();
    void layoutUpdateFinished();
    void itemGeometryChanged(int index, const QRect& newGeometry);

private slots:
    void onAnimationFinished();
    void onThrottledUpdate();

private:
    struct LayoutItemInfo {
        QLayoutItem* item;
        QRect currentGeometry;
        QRect targetGeometry;
        QPropertyAnimation* animation;
        bool isAnimating;

        LayoutItemInfo(QLayoutItem* layoutItem = nullptr)
            : item(layoutItem)
            , animation(nullptr)
            , isAnimating(false)
        {}
    };

    struct LayoutCache {
        QSize lastContainerSize;
        SonyIveDesign::DisplayMode lastDisplayMode;
        int lastColumns;
        QList<QRect> cachedGeometries;
        bool isValid;

        LayoutCache() : lastColumns(0), isValid(false) {}

        void invalidate() { isValid = false; }
    };

    // === 核心布局计算 ===
    void calculateLayout(const QRect& rect);
    void calculateGridLayout(const QRect& rect, QList<QRect>& geometries);
    void adjustSpacingForMode(SonyIveDesign::DisplayMode mode);

    // === 动画系统 ===
    void animateToNewLayout(const QList<QRect>& newGeometries);
    void createItemAnimation(LayoutItemInfo& info, const QRect& targetGeometry);
    void stopAllAnimations();

    // === 优化机制 ===
    bool shouldUseCache(const QRect& rect) const;
    void updateCache(const QRect& rect, const QList<QRect>& geometries);
    void throttleLayoutUpdate();

    // === 工具方法 ===
    int getAdaptiveSpacing(SonyIveDesign::DisplayMode mode) const;
    QMargins getAdaptiveMargins(SonyIveDesign::DisplayMode mode) const;
    void ensureValidItemCount();

    // === 核心成员变量 ===
    ResponsiveFileListEngine* m_engine;
    QList<LayoutItemInfo> m_items;

    // === 布局参数 ===
    int m_columns;
    int m_spacing;
    QMargins m_margins;
    QRect m_lastGeometry;

    // === 动画系统 ===
    bool m_animationEnabled;
    int m_animationDuration;
    QParallelAnimationGroup* m_animationGroup;
    int m_activeAnimations;

    // === 性能优化 ===
    bool m_performanceMode;
    QTimer* m_updateTimer;
    int m_throttleInterval;
    bool m_layoutInvalid;
    LayoutCache m_cache;

    // === 状态管理 ===
    SonyIveDesign::DisplayMode m_currentDisplayMode;
    bool m_isUpdating;

#endif // ADAPTIVEFILELAYOUT_H